package com.tank.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * User: SuQiEr
 * Date:2017/8/5 0005
 * Time: 上午 11:11
 * To change this template use File | Settings | File Templates.
 */
public class ByteBufferTest {

    public static void main(String[] args) throws IOException {
        testScattering();
    }

    public static  void testScattering() throws IOException {

        //服务端开启一个端口
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        InetSocketAddress inetSocketAddress =new  InetSocketAddress(9999);
        serverSocketChannel.socket().bind(inetSocketAddress);
        //定义数组模拟 协议 head body
        int length = 2+3+4;
        ByteBuffer[] buffers = new ByteBuffer[3];
        buffers[0] = ByteBuffer.allocate(2);
        buffers[1] = ByteBuffer.allocate(3);
        buffers[2] = ByteBuffer.allocate(4);

        SocketChannel accept =  serverSocketChannel.accept();

        while (true){
            int readSize = 0;
            //从channel中读取到buffer
            while (readSize < length){
                readSize += accept.read(buffers);
                Arrays.asList(buffers).stream()
                        .map(buffer -> "position:"+buffer.position()+" limit:"+buffer.limit())
                        .forEach(System.out::println);
            }
            //buffer 反转
            Arrays.asList(buffers).forEach(buffer -> buffer.flip());

            //从buffer中写入到channel
            int writeSize = 0;
            while (writeSize < length){
                writeSize += accept.write(buffers);
                Arrays.asList(buffers).stream()
                        .map(buffer -> "position:"+buffer.position()+" limit:"+buffer.limit())
                        .forEach(System.out::println);
            }
            //buffer 清空
            Arrays.asList(buffers).forEach(buffer -> buffer.clear());
        }


    }
}
